<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>车位管理系统</title>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    table { width: 100%; border-collapse: collapse; margin-top: 20px; }
    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
    th { background-color: #f2f2f2; }
    .form-group { margin-bottom: 10px; }
    button { padding: 5px 10px; cursor: pointer; }
  </style>
</head>
<body>
<h1>车位管理系统</h1>

<div>
  <h2>车位查询</h2>
  <div class="form-group">
    <label>车位编号: </label>
    <input type="text" id="spaceNumber" placeholder="输入车位编号">
  </div>
  <div class="form-group">
    <label>区域: </label>
    <input type="text" id="area" placeholder="输入区域">
  </div>
  <button onclick="searchSpaces()">查询</button>

  <div>
    <p>空闲车位数量: <span id="availableCount">0</span></p>
  </div>
</div>

<div>
  <h2>车位列表</h2>
  <table id="parkingTable">
    <thead>
    <tr>
      <th>车位编号</th>
      <th>区域</th>
      <th>状态</th>
      <th>车牌号</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>

<div id="assignForm" style="display: none; margin-top: 20px;">
  <h2>分配车位</h2>
  <div class="form-group">
    <label>车牌号: </label>
    <input type="text" id="plateNumber" placeholder="输入车牌号">
  </div>
  <div class="form-group">
    <label>车主姓名: </label>
    <input type="text" id="owner" placeholder="输入车主姓名">
  </div>
  <button onclick="assignSpace()">确认分配</button>
  <button onclick="cancelAssign()">取消</button>
</div>

<script>
  let currentSpaceId = null;

  // 页面加载时获取所有车位信息
  document.addEventListener('DOMContentLoaded', function() {
    fetchAllSpaces();
    updateAvailableCount();
  });

  // 获取所有车位信息
  function fetchAllSpaces() {
    axios.get('/api/parking-spaces')
            .then(response => {
              renderParkingTable(response.data);
            })
            .catch(error => {
              console.error('获取车位信息失败:', error);
            });
  }

  // 条件查询车位
  function searchSpaces() {
    const spaceNumber = document.getElementById('spaceNumber').value;
    const area = document.getElementById('area').value;

    axios.get('/api/parking-spaces/search', {
      params: { spaceNumber, area }
    })
            .then(response => {
              renderParkingTable(response.data);
            })
            .catch(error => {
              console.error('查询车位失败:', error);
            });
  }

  // 更新空闲车位数量
  function updateAvailableCount() {
    axios.get('/api/parking-spaces/available-count')
            .then(response => {
              document.getElementById('availableCount').textContent = response.data;
            })
            .catch(error => {
              console.error('获取空闲车位数量失败:', error);
            });
  }

  // 显示分配表单
  function showAssignForm(spaceId) {
    currentSpaceId = spaceId;
    document.getElementById('assignForm').style.display = 'block';
  }

  // 取消分配
  function cancelAssign() {
    document.getElementById('assignForm').style.display = 'none';
    currentSpaceId = null;
  }

  // 分配车位
  function assignSpace() {
    const plateNumber = document.getElementById('plateNumber').value;
    const owner = document.getElementById('owner').value;

    if (!plateNumber) {
      alert('请输入车牌号');
      return;
    }

    const vehicle = { plateNumber, owner };

    axios.post(`/api/parking-spaces/${currentSpaceId}/assign`, vehicle)
            .then(response => {
              if (response.data) {
                alert('分配成功');
                fetchAllSpaces();
                updateAvailableCount();
                cancelAssign();
              } else {
                alert('分配失败，车位可能已被占用');
              }
            })
            .catch(error => {
              console.error('分配车位失败:', error);
              alert('分配失败');
            });
  }

  // 回收车位
  function releaseSpace(spaceId) {
    if (confirm('确定要回收该车位吗？')) {
      axios.post(`/api/parking-spaces/${spaceId}/release`)
              .then(response => {
                if (response.data) {
                  alert('回收成功');
                  fetchAllSpaces();
                  updateAvailableCount();
                } else {
                  alert('回收失败，车位可能已经是空闲状态');
                }
              })
              .catch(error => {
                console.error('回收车位失败:', error);
                alert('回收失败');
              });
    }
  }

  // 渲染车位表格
  function renderParkingTable(spaces) {
    const tbody = document.querySelector('#parkingTable tbody');
    tbody.innerHTML = '';

    spaces.forEach(space => {
      const row = document.createElement('tr');

      row.innerHTML = `
                    <td>${space.spaceNumber}</td>
                    <td>${space.area}</td>
                    <td>${space.status}</td>
                    <td>${space.vehicle ? space.vehicle.plateNumber : '-'}</td>
                    <td>
                        ${space.status === '空闲' ?
              `<button onclick="showAssignForm(${space.id})">分配</button>` :
              `<button onclick="releaseSpace(${space.id})">回收</button>`}
                    </td>
                `;

      tbody.appendChild(row);
    });
  }
</script>
</body>
</html>